package cn.crex1.xiaomi.core.orm.druid;

import java.io.IOException;
import java.io.InputStream;
import java.sql.Connection;
import java.sql.SQLException;
import java.util.Properties;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.alibaba.druid.pool.DruidDataSource;
import com.alibaba.druid.pool.DruidDataSourceFactory;
import com.alibaba.druid.pool.DruidPooledConnection;

public class DruidCocfig {

	private static DruidDataSource dataSource=null;
	
	private static Logger logger=LoggerFactory.getLogger(DruidCocfig.class);
	
	//暂存当前连接
	private ThreadLocal<Connection> currentConn=new ThreadLocal<>();
	
	//静态代码块加载数据库配置文件
	static {
		Properties p=loadPropertiesFile("jdbc.properties");
		try {
			//创建druid数据库连接池
			dataSource=(DruidDataSource) DruidDataSourceFactory.createDataSource(p);
		} catch (Exception e) {
			logger.error("配置文件载入失败");
			e.printStackTrace();
		}
	}
	//获取配置文件
	private static Properties loadPropertiesFile(String filename) {
		InputStream in = DruidCocfig.class.getClassLoader().getResourceAsStream(filename);
		Properties properties=new Properties();
		try {
			properties.load(in);
			logger.debug("载入配置文件");
		} catch (IOException e) {
			e.printStackTrace();
		}
		return properties;
	}
	//打开数据库连接
	public Connection openConn() {
		try {
			logger.debug("open a connection");			
			
			Connection connection = dataSource.getConnection();
			currentConn.set(connection);
			return connection;
		} catch (SQLException e) {
			e.printStackTrace();
		}
		logger.error("open connection failed ");
		return null;
	}
	//关闭数据库连接
	public void closeConnection(Connection connection) {
		try {
			connection.close();
			currentConn.remove();
			logger.debug("close Connection");
		} catch (SQLException e) {
			e.printStackTrace();
		}
	}
	public ThreadLocal<Connection> getCurrentConn() {
		return currentConn;
	}
}
